﻿using System;
using System.Collections.Generic;

namespace MvvmUtils.ViewModels
{
    public interface IProperty
    {
        string Name { get; }
    }

    public class Property<TValue> : IProperty
    {
        private readonly string _name;

        private IEqualityComparer<TValue> _comparer = EqualityComparer<TValue>.Default;

        private readonly ViewModel _owner;

        private TValue _value;

        public Property(string name, ViewModel owner)
        {
            if (owner == null) throw new ArgumentNullException("owner");
            if (string.IsNullOrEmpty(name)) throw new ArgumentException("Empty name.", "name");

            _name = name;
            _owner = owner;
        }

        public string Name
        {
            get { return _name; }
        }

        public TValue GetValue()
        {
            return _value;
        }

        public void SetValue(TValue value)
        {
            if (_comparer.Equals(_value, value))
            {
                return;
            }

            _value = value;
            _owner.OnPropertyChanged(this);
        }

        public Property<TValue> WithComparer(IEqualityComparer<TValue> comparer)
        {
            if (comparer != null)
            {
                _comparer = comparer;
            }

            return this;
        }
    }
}